package cn.kilo.trigger.http.user;

import cn.kilo.domain.model.login.vo.LoginVo;
import cn.kilo.domain.model.login.vo.RegisterVO;
import cn.kilo.domain.model.login.vo.UserVO;
import cn.kilo.domain.model.order.entity.OrderEntity;
import cn.kilo.domain.model.order.entity.StaffEntity;
import cn.kilo.domain.model.order.entity.UserEntity;
import cn.kilo.domain.model.order.res.JudgeOfProblemRes;
import cn.kilo.domain.model.order.res.StaffResOfRegister;
import cn.kilo.domain.model.order.res.UserRes;
import cn.kilo.domain.repository.IStrategyRepository;
import cn.kilo.domain.service.user.IUserService;
import cn.kilo.trigger.api.dto.user.UserDTO;
import cn.kilo.types.common.Constants;
import cn.kilo.types.enums.ResponseCode;
import cn.kilo.types.model.Response;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.boot.web.reactive.context.ReactiveWebServerApplicationContext;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.concurrent.locks.Condition;

/**
 * @author kilok
 */
@Slf4j
@RestController
@CrossOrigin("*")
@RequestMapping("/api/user")
public class UserController implements cn.kilo.trigger.api.IUserService {

    @Resource
    private IUserService userService;

    @Resource
    private IStrategyRepository repository;

    @PostMapping("/login")
    @Override
    public Response<?> login(@RequestBody UserDTO userDTO) {
        try {
            log.info("开始登录:{}", userDTO);
            return userService.login(LoginVo.builder()
                    .stuId(userDTO.getStuId()).password(userDTO.getPassword())
                    .build());
        } catch (Exception e) {
            e.printStackTrace();
            log.info("登录失败 :{}", userDTO);
            return Response.<Boolean>builder().code(ResponseCode.UN_ERROR.getCode()).info(ResponseCode.UN_ERROR.getInfo()).build();
        }
    }

    @PostMapping("/register")
    @Override
    public Response<?> register(@RequestBody UserDTO userDTO) {
        try {
            boolean res = userService.register(
                    RegisterVO.builder()
                            .stuId(userDTO.getStuId())
                            .password(userDTO.getPassword())
                            .floor(userDTO.getFloor())
                            .ridgepole(userDTO.getRidgepole())
                            .roomNumber(userDTO.getRoomNumber())
                            .nickName(userDTO.getNickName())
                            .grade(userDTO.getGrade())
                            .studentInfo(userDTO.getStudentInfo())
                            .build());
            if (res) {
                return Response.<String>builder().code(ResponseCode.SUCCESS.getCode()).info(ResponseCode.SUCCESS.getInfo()).data("用户注册成功").build();
            } else {
                return Response.<String>builder().code(ResponseCode.UN_ERROR.getCode()).info(ResponseCode.UN_ERROR.getInfo()).data("注册失败，用户名重复").build();
            }
        } catch (Exception e) {
            log.info("注册失败:{}", userDTO);
            return Response.<String>builder().code(ResponseCode.UN_ERROR.getCode()).info(ResponseCode.UN_ERROR.getInfo()).data("注册失败").build();
        }
    }

    @PostMapping("/updateImage")
    @ApiImplicitParams({@ApiImplicitParam(name = "image", value = "MultipartFile")})
    @Override
    @CrossOrigin("*")
    public Response<?> updateImage(String userId, MultipartFile image) {
        try {
            // TODO: 2024/5/8 采用OSS存储用户图片
            String res = userService.updateUserImage(image, userId);
            return Response.<String>builder().code(ResponseCode.SUCCESS.getCode()).info(ResponseCode.SUCCESS.getInfo()).data(res).build();
        } catch (Exception e) {
            e.printStackTrace();
            log.info("头像上传失败:{}", image);
            return Response.<String>builder().code(ResponseCode.UN_ERROR.getCode()).info(ResponseCode.UN_ERROR.getInfo()).data("图片文件过大，上传失败").build();
        }
    }

    /**
     * 更新用户信息
     *
     * @param userDTO
     * @return
     */
    @PostMapping("/updateUserInfo")
    @Override
    public Response<?> updateUserInfo(@RequestBody UserDTO userDTO) {
        try {
            Boolean res = userService.updateUserInfo(
                    UserVO.builder().userId(userDTO.getUserId())
                            .nickName(userDTO.getNickName()).password(userDTO.getPassword()).floor(userDTO.getFloor()).ridgepole(userDTO.getRidgepole()).roomNumber(userDTO.getRoomNumber()).build());
            if (res) {
                return Response.<String>builder().code(ResponseCode.SUCCESS.getCode()).info(ResponseCode.SUCCESS.getInfo()).data("用户信息更改成功").build();
            } else {
                return Response.<String>builder().code(ResponseCode.UN_ERROR.getCode()).info(ResponseCode.UN_ERROR.getInfo()).data("用户信息更改失败,用户名重复").build();
            }
        } catch (Exception e) {
            log.info("用户信息更新失败:{}", userDTO);
            return Response.<String>builder().code(ResponseCode.UN_ERROR.getCode()).info(ResponseCode.UN_ERROR.getInfo()).data("用户信息更改失败--未知错误").build();
        }
    }

    /**
     * 查询用户信息
     *
     * @param userDTO
     * @return
     */
    @PostMapping("/getUserInformation")
    @Override
    public Response<?> getUserInformation(@RequestBody UserDTO userDTO) {
        try {
            log.info("查询用户信息:{}", userDTO);
            UserRes userInformation = repository.getUserInformation(userDTO.getUserId());
            return Response.<UserRes>builder().code(ResponseCode.SUCCESS.getCode()).info(ResponseCode.SUCCESS.getInfo()).data(userInformation).build();
        } catch (Exception e) {
            log.info("查询失败");
            return Response.<String>builder().code(ResponseCode.UN_ERROR.getCode()).info(ResponseCode.UN_ERROR.getInfo()).data("用户信息查询失败").build();
        }
    }

    /**
     * 查询用户角色
     *
     * @param userDTO
     * @return
     */
    @Override
    public Response<?> getUserRole(UserDTO userDTO) {
        try {
            String role = userService.getUserRole(userDTO.getUserId());
            return Response.<String>builder().code(ResponseCode.SUCCESS.getCode()).info(ResponseCode.SUCCESS.getInfo()).data(role).build();
        } catch (Exception e) {
            log.info(":", e);
            return Response.<String>builder().code(ResponseCode.UN_ERROR.getCode()).info(ResponseCode.UN_ERROR.getInfo()).data("用户角色获取失败").build();
        }
    }

    @PostMapping("/registerToStaff")
    @Override
    public Response<?> registerToStaff(@RequestBody UserDTO userDTO) {
        try {
            log.info("入参信息:{}",userDTO);
            StaffEntity staffEntity = userService.registerToStaff(UserEntity.builder()
                    .userId(userDTO.getUserId())
                    .userName(userDTO.getUserName())
                    .phoneNumber(userDTO.getPhoneNumber())
                    .payNickName(userDTO.getPayNickName())
                    .payAccount(userDTO.getPayAccount())
                    .build());
            if(staffEntity!=null){
                StaffResOfRegister staffResOfRegister=new StaffResOfRegister();
                BeanUtils.copyProperties(staffEntity,staffResOfRegister);
                return Response.<StaffResOfRegister>builder()
                        .code(ResponseCode.SUCCESS.getCode())
                        .info(ResponseCode.SUCCESS.getInfo())
                        .data(staffResOfRegister)
                        .build();

            }
            return Response.<String>builder()
                    .code(ResponseCode.UN_ERROR.getCode())
                    .info(ResponseCode.UN_ERROR.getInfo())
                    .data("员工注册失败")
                    .build();
        } catch (Exception e) {
            return Response.<String>builder()
                    .code(ResponseCode.UN_ERROR.getCode())
                    .info(ResponseCode.UN_ERROR.getInfo())
                    .data("员工注册失败")
                    .build();
        }
    }

    /**
     * 用户注册成为员工，只能申请明天的 申请成为员工只能在计算员工薪资和清除暂时员工之后才能进行 清除员工的同时更新对应的员工数量
     *
     * @param userDTO
     * @return
     */
    @PostMapping("/beStaff")
    @Override
    public Response<?> beStaff(@RequestBody UserDTO userDTO) {
        try {
            Boolean res = userService.beStaff(StaffEntity.builder()
                    .staffId(userDTO.getStaffId())
                    .role(userDTO.getRole())
                    .workTime(userDTO.getWorkTime())
                    .ridgepole(userDTO.getRidgepole())
                    .value(userDTO.getValue())
                    .status(userDTO.getStaffTime())
                    .type(userDTO.getType()).build());
            if (res) {
                return Response.<String>builder().code(ResponseCode.SUCCESS.getCode()).info(ResponseCode.SUCCESS.getInfo()).data("员工注册成功，请履行对应的职责").build();
            } else {
                return Response.<String>builder().code(ResponseCode.UN_ERROR.getCode()).info(ResponseCode.UN_ERROR.getInfo()).data("员工已注册员工或者该职位已满员，不可再次注册").build();
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Response.<String>builder().code(ResponseCode.UN_ERROR.getCode()).info(ResponseCode.UN_ERROR.getInfo()).data("申请注册失败").build();
        }
    }

    @PostMapping("/setLocation")
    @Override
    public Response<?> setLocation(@RequestBody UserDTO userDTO) {
        try {
            boolean b = userService.setLocation(UserEntity.builder()
                    .userId(userDTO.getUserId())
                    .nickName(userDTO.getNickName())
                    .userName(userDTO.getUserName())
                    .phoneNumber(userDTO.getPhoneNumber())
                    .roomNumber(userDTO.getRoomNumber())
                    .build());
            if(b){
                return Response.<String>builder()
                        .code(ResponseCode.SUCCESS.getCode())
                        .info(ResponseCode.SUCCESS.getInfo())
                        .data("位置信息设置成功")
                        .build();
            }
            return Response.<String>builder().code(ResponseCode.UN_ERROR.getCode())
                    .info(ResponseCode.UN_ERROR.getInfo())
                    .data("位置信息设置失败,请重试")
                    .build();
        } catch (Exception e) {
            e.printStackTrace();
            return Response.<String>builder().code(ResponseCode.UN_ERROR.getCode())
                    .info(ResponseCode.UN_ERROR.getInfo())
                    .data("位置信息设置失败,请重试")
                    .build();
        }
    }

    @GetMapping("/privatePolicy")
    @Override
    public Response<?> getPrivatePolicy() {
        try {
            String res= Constants.Policy.PRIVATE;
            return Response.<String>builder()
                    .code(ResponseCode.SUCCESS.getCode())
                    .info(ResponseCode.SUCCESS.getInfo())
                    .data(res)
                    .build();
        } catch (Exception e) {
            return Response.<String>builder().code(ResponseCode.UN_ERROR.getCode())
                    .info(ResponseCode.UN_ERROR.getInfo())
                    .data("隐私政策获取失败")
                    .build();
        }
    }
    @GetMapping("/agreement")
    @Override
    public Response<?> getAgreement() {
        try {
            String res= Constants.Policy.agreement;
            return Response.<String>builder()
                    .code(ResponseCode.SUCCESS.getCode())
                    .info(ResponseCode.SUCCESS.getInfo())
                    .data(res)
                    .build();
        } catch (Exception e) {
            return Response.<String>builder().code(ResponseCode.UN_ERROR.getCode())
                    .info(ResponseCode.UN_ERROR.getInfo())
                    .data("用户协议获取失败")
                    .build();
        }
    }

    @PostMapping("problems")
    @Override
    public Response<?> problem(@RequestBody UserDTO userDTO) {
        try {
            JudgeOfProblemRes problem = userService.problem(UserEntity
                    .builder()
                    .userId(userDTO.getUserId())
                    .info(userDTO.getInfo())
                    .build());
            return Response.<JudgeOfProblemRes>builder()
                    .code(ResponseCode.SUCCESS.getCode())
                    .info(ResponseCode.SUCCESS.getInfo())
                    .data(problem)
                    .build();
        } catch (Exception e) {
            return Response.<String>builder()
                    .code(ResponseCode.UN_ERROR.getCode())
                    .info(ResponseCode.UN_ERROR.getInfo())
                    .data("问题反馈失败")
                    .build();
        }
    }

    @PostMapping("/problemPicture")
    @ApiImplicitParams({@ApiImplicitParam(name = "image", value = "MultipartFile")})
    @Override
    @CrossOrigin("*")
    public Response<?> problemPicture(String judgeId,
                                      MultipartFile image) {
        try {
            String url = userService.problemPicture(judgeId, image);
            if(null==url){
                return Response.<String>builder()
                        .code(ResponseCode.UN_ERROR.getCode())
                        .info(ResponseCode.UN_ERROR.getInfo())
                        .data("图片上传失败")
                        .build();
            }
            return Response.<String>builder()
                    .code(ResponseCode.SUCCESS.getCode())
                    .info(ResponseCode.SUCCESS.getInfo())
                    .data(url)
                    .build();
        } catch (Exception e) {
            return Response.<String>builder()
                    .code(ResponseCode.UN_ERROR.getCode())
                    .info(ResponseCode.UN_ERROR.getInfo())
                    .data("图片上传失败")
                    .build();
        }

    }

    @PostMapping("/setPost")
    @Override
    public Response<?> setPost(@RequestBody UserDTO userDTO) {
        try {
            boolean res = userService.setPost(UserEntity.builder()
                    .post(userDTO.getPost())
                    .userId(userDTO.getUserId())
                    .build());
            if(res){
                return Response.<String>builder()
                        .code(ResponseCode.SUCCESS.getCode())
                        .info(ResponseCode.SUCCESS.getInfo())
                        .data("通知设置成功")
                        .build();
            }
            return Response.<String>builder()
                    .code(ResponseCode.UN_ERROR.getCode())
                    .info(ResponseCode.UN_ERROR.getInfo())
                    .data("通知设置失败")
                    .build();
        } catch (Exception e) {
            return Response.<String>builder()
                    .code(ResponseCode.UN_ERROR.getCode())
                    .info(ResponseCode.UN_ERROR.getInfo())
                    .data("通知设置失败")
                    .build();
        }
    }

    // TODO: 2024/6/23 完善用户获取所有订单信息接口
    @PostMapping("/getAllOrder")
    @Override
    public Response<?> getAllOrder(@RequestBody UserDTO userDTO) {
        try {
            userService.getAllOrder(OrderEntity.builder()
                            .userId(userDTO.getUserId())
                    .build());
            return null;
        } catch (Exception e) {
            return Response.<String>builder()
                    .code(ResponseCode.UN_ERROR.getCode())
                    .info(ResponseCode.UN_ERROR.getInfo())
                    .data("订单历史获取失败")
                    .build();
        }
    }

    public Response<?> test() {
        try {
            return null;
        } catch (Exception e) {
            return Response.<String>builder()
                    .code(ResponseCode.UN_ERROR.getCode())
                    .info(ResponseCode.UN_ERROR.getInfo())
                    .data("")
                    .build();
        }
    }
}
